import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { getEnterprises, bindEnterprises } from './service';
import { message } from 'antd';
import { TableListData } from './data.d';

const R = require('ramda');

export interface StateType {
  data: TableListData;
  pagination: any;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
    add: Effect;
  };
  reducers: {
    refreshState: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'manageEnterpriseJoinEnterprise',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *getEnterprises({ payload }, { call, put }) {
      const response = yield call(getEnterprises, { ...payload });
      if (response && response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            data: {
              list: response.content,
              pagination: {},
            },
          },
        });
      } else {
        if (payload.onFail) payload.onFail();
      }
    },

    *bindEnterprises({ payload }, { call }) {
      const response = yield call(bindEnterprises, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (response && response.resultCode === 'ok') {
        message.info('加入企业申请已提交，请耐心等候');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        if (payload.onFail) payload.onFail();
      }
    },
  },

  reducers: {
    /**
     * 刷新state
     *
     * @param state
     */
    refreshState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};

export default Model;
